package com.unicdata.ai.demo_2af.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unicdata.ai.demo_2af.common.entity.User;
import com.unicdata.ai.demo_2af.common.entity.UserRole;
import com.unicdata.ai.demo_2af.common.exception.BusinessException;
import com.unicdata.ai.demo_2af.common.utils.PasswordUtils;
import com.unicdata.ai.demo_2af.mapper.UserMapper;
import com.unicdata.ai.demo_2af.mapper.UserRoleMapper;
import com.unicdata.ai.demo_2af.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户服务实现类
 *
 * @author lhn
 * @date 2025/06/25 16:52
 * @since 1.0.0
 **/
@Service
public class UserServiceImpl extends ServiceImpl <UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public User getUserByUsername(String username) {
        if (StringUtils.isBlank(username)) {
            return null;
        }

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper <>();
        queryWrapper.eq(User::getUsername, username);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public List <String> getUserRoles(Long userId) {
        if (userId == null) {
            return new ArrayList <>();
        }
        return userMapper.selectRolesByUserId(userId);
    }

    @Override
    public List<String> getUserPermissions(Long userId) {
        if (userId == null) {
            return new ArrayList<>();
        }
        return userMapper.selectPermissionsByUserId(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean register(User user) {
        if (user == null) {
            throw new BusinessException("用户信息不能为空");
        }
        if (StringUtils.isBlank(user.getUsername())) {
            throw new BusinessException("用户名不能为空");
        }
        if (StringUtils.isBlank(user.getPassword())) {
            throw new BusinessException("密码不能为空");
        }

        // 检查用户名是否已存在
        User existUser = getUserByUsername(user.getUsername());
        if (existUser != null) {
            throw new BusinessException("用户名已存在");
        }

        // 生成盐值
        String salt = PasswordUtils.generateSalt();
        // 加密密码
        String encryptPassword = PasswordUtils.encryptPassword(user.getPassword(), salt);

        // 设置用户信息
        user.setSalt(salt);
        user.setPassword(encryptPassword);
        user.setStatus(1); // 正常状态
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        user.setPwdUpdateTime(new Date());
        user.setLoginFailCount(0);
        user.setIsLocked(0);

        return save(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePassword(Long userId, String oldPassword, String newPassword) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        if (StringUtils.isBlank(oldPassword)) {
            throw new BusinessException("旧密码不能为空");
        }
        if (StringUtils.isBlank(newPassword)) {
            throw new BusinessException("新密码不能为空");
        }

        // 获取用户信息
        User user = getById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 验证旧密码是否正确
        if (!PasswordUtils.matches(oldPassword, user.getSalt(), user.getPassword())) {
            throw new BusinessException("旧密码错误");
        }

        // 生成新的盐值和密码
        String newSalt = PasswordUtils.generateSalt();
        String encryptNewPassword = PasswordUtils.encryptPassword(newPassword, newSalt);

        // 更新密码
        user.setSalt(newSalt);
        user.setPassword(encryptNewPassword);
        user.setPwdUpdateTime(new Date());
        user.setUpdateTime(new Date());

        return updateById(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean assignRoles(Long userId, List<Long> roleIds) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        if (roleIds == null) {
            roleIds = new ArrayList<>();
        }

        // 查询用户是否存在
        User user = getById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 删除原有角色关联
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId, userId);
        userRoleMapper.delete(queryWrapper);

        // 添加新角色关联
        if (!roleIds.isEmpty()) {
            for (Long roleId : roleIds) {
                UserRole userRole = new UserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                userRole.setCreateTime(new Date());
                userRoleMapper.insert(userRole);
            }
        }
        return true;
    }
}